package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.google.common.base.Predicates;
import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	// 注入
	@Autowired
	private AreaService areaService;
	private File file;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * 导入数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "area_upload")
	public String AreaUpload() throws Exception {
		List<Area> areaList = new ArrayList<Area>();
		// 这里我们需要使用加载excel文件
		HSSFWorkbook hssfWorkBook = new HSSFWorkbook(new FileInputStream(file));
		// 读取其中一个xls文件
		HSSFSheet sheetAt = hssfWorkBook.getSheetAt(0);
		// 我们要对这个文件进行遍历找到其中的一行数据放到集合数组中
		for (Row row : sheetAt) {
			if (row.getRowNum() == 0) {
				// 这是第一行我们可以跳过了
				continue;
			}
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			//进行切分
			province = province.substring(0, province.length()-1);
			city = city.substring(0, city.length()-1);
			district = district.substring(0, district.length()-1);
			//将它们拼接再一起
			String[] headByString = PinYin4jUtils.getHeadByString(province+city+district);
			//将数组转为集合
			StringBuffer buffer = new StringBuffer();
			for (String headBy : headByString) {
				buffer.append(headBy);
			}
			String shorthard = buffer.toString();
			area.setShortcode(shorthard);
			
			String citycode = PinYin4jUtils.hanziToPinyin(city,"");
			area.setCitycode(citycode);
			// 将我们封装的数据放到我们的集合里面
			areaList.add(area);
		}
		// 现在我们需要将数据提交给我们的业务层
		areaService.save(areaList);
		return NONE;
	}

	// 分页查询
	private Integer rows;
	private Integer page;

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	@Action(value = "area_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<Area> specifications = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (StringUtils.isNoneBlank(model.getProvince())) {
					Predicate p1 = cb.like(root.get("province").as(String.class), "%"+model.getProvince()+"%");
					list.add(p1);
				}
				if(StringUtils.isNoneBlank(model.getCity())){
					Predicate p2= cb.like(root.get("city").as(String.class),"%"+model.getCity()+"%");
					list.add(p2);
				}
				if(StringUtils.isNoneBlank(model.getDistrict())){
					Predicate p3 = cb.like(root.get("district").as(String.class), model.getPostcode());
					list.add(p3);	
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<Area> pageList = areaService.findPageDate(specifications,pageable);
		//返回的数据写成我们想要的数据
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("totle", pageList.getTotalElements());
		result.put("rows", pageList.getContent());
		//转为json数据，
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
	/*
	 * 添加数据
	 */
	@Action(value="area_save",results={@Result(name="success",type="redirect",location="/pages/base/area.html")})
	public String save(){
		//直接进行数据添加
		areaService.saveArea(model);
		return SUCCESS;
	}
	/**
	 * area_findAll
	 */
	@Action(value="area_findAll",results={@Result(name="success",type="json")})
	public String subArea_findALL(){
		List<Area> listArea = areaService.subArea_findALL();
		//压入栈顶
		ActionContext.getContext().getValueStack().push(listArea);
		return SUCCESS;
	}
}
